<?php declare(strict_types=1);

namespace app\common\service;

use app\common\model\House;
use app\common\model\Cases;

class HouseService
{

    /**
     * 获取热装楼盘
     * @param array $map 条件
     * @param int $pageSize 条数
     * @return void
     */
    public function getDataList(array $map, int $pageSize = DEFAULT_PAGE_SIZE, $page = 1, ...$args)
    {
        $model = new House();
        $items = $model
            ->field(['id','name','thumb_url','custom_num','start_num','completed_num','tag_ids','house_type','area','address','views'])
            ->where(['status'=>1])
            ->where(function ($query) use ($map, $args) {
                if(!empty($map)){
                    foreach ($map as $key=>$value) {
                        $query->where($key, $value);
                    }
                }
                if (!empty($args)) {
                    foreach ($args as $arg) {
                        if ($arg) {
                            $query->where('name|address', $arg);
                        }
                    }
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate(['list_rows'=>$pageSize])
            ->each(function($item) {
                $item['tag_name'] = (new TagService())->getTagName($item->tag_ids);
                return $item;
            });
        return $items;
    }

    /**
     * 详情页
     * @param $id
     * @return void
     */
    public function getDetail($id)
    {
        $model = new House();
        $item = $model->where('id', $id)->findOrEmpty()->toArray();
        if ($item['images_url']) {
            $item['images_url'] = explode(';', rtrim($item['images_url'], ';'));
        }
        return $item;
    }

    /**
     * 获取相关案例
     * @param string $house 楼盘名称
     * @param int $page
     * @return void
     */
    public function getRelevantCase(string $house, int $page = 4)
    {
        $model = new Cases();
        $items = $model->where('house', $house)->limit($page)->select();
        if ($items) {
            $items->toArray();
        }

        return $items ?? [];
    }
}